package com.star.robot.wxpay;

import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;

/**
 * Created by mawenlong on 2019/6/14.
 */
public final class WebUtils extends org.springframework.web.util.WebUtils {
    private WebUtils() {
    }

    public static String getRequestUri(HttpServletRequest request) {
        String url = request.getRequestURI();
        String queryString = request.getQueryString();
        if(queryString != null && !"".equals(queryString)) {
            url = url + "?" + queryString;
        }

        return url;
    }

    public static String getClientIp(HttpServletRequest request) {
        Assert.notNull(request);
        String ip = request.getHeader("X-Forwarded-For");
        if(isValidIp(ip)) {
            if(!ip.contains(",")) {
                return ip.trim();
            }

            String[] ips = ip.split(",");
            if(ips != null && ips.length > 0 && isValidIp(ips[0])) {
                return ips[0].trim();
            }
        }

        ip = request.getHeader("X-Real-IP");
        if(isValidIp(ip)) {
            return ip.trim();
        } else {
            ip = request.getHeader("Proxy-Client-IP");
            if(isValidIp(ip)) {
                return ip.trim();
            } else {
                ip = request.getHeader("WL-Proxy-Client-IP");
                return isValidIp(ip)?ip.trim():request.getRemoteAddr();
            }
        }
    }

    private static boolean isValidIp(String ip) {
        return (ip!= null && !"".equals(ip)) && !"unknown".equalsIgnoreCase(ip.trim());
    }
}
